package com.mystore.common.utils.security;

import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {
    public static String getMd5(String str){
        if(!StringUtils.hasLength(str))
            return null;
        byte[] source=str.getBytes();
        MessageDigest instance = null;
        try {
            instance = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        instance.update(source);
        byte [] b;
        b= instance.digest();
        return toHashString(b);
    }
    public static String toHashString(byte[] bytes){
        if(bytes==null||bytes.length==0)
            return null;
        StringBuffer buf = new StringBuffer("");
        int i;
        for (int offset = 0; offset < bytes.length; offset++) {
            i = bytes[offset];
            if (i < 0)
                i += 256;
            int id1=i/16;
            int id2=i%16;
            buf.append(Integer.toHexString(id1)).append(Integer.toHexString(id2));
        }
        return buf.toString();
    }
}
